package itstudio.instructor.ui;

import itstudio.app.wq.R;
import itstudio.instructor.adapter.AddImageAdapter;
import itstudio.instructor.config.Config;
import itstudio.instructor.config.MyApplication;
import itstudio.instructor.entity.News;
import itstudio.instructor.http.TwitterRestClient;
import itstudio.instructor.image.local.localImageFirstActivity;
import itstudio.instructor.service.DatebaseService;
import itstudio.instructor.util.BitMapUtil;
import itstudio.instructor.util.FileUtil;
import itstudio.instructor.util.TimeUtil;
import itstudio.instructor.util.ToastUtil;
import itstudio.instructor.widget.ActionSheetPic;
import itstudio.instructor.widget.ActionSheetPic.OnActionSheetSelected;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import me.storm.ninegag.view.swipeback.ImageViewActivity;
import org.apache.http.Header;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class DraftsEditActivity extends Activity implements
		OnActionSheetSelected {

	//
	private Context context;
	// 获取到下载url后，直接复制给MapApp,里面的全局变量

	EditText title_et = null;
	EditText content_et = null;
	TextView send_tv = null;
	TextView tv_save_drafts = null;
	private String id=null;
	private String picstr=null;
	private String photPath; // 拍照保存 的图片位置
	private String newPicPath = null; // 上传的图片位置
	private int newsPicNum; // 待上传的图片个数
	GridView gridview;
	String allPath;

	DisplayImageOptions options;
	private List<String> picList = new ArrayList<String>();
	Bitmap bitmap;
	private LinearLayout backlayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context = DraftsEditActivity.this;

		if (picList.size() == 0) {

			picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
		}
		setContentView(R.layout.activity_draf_detail);
		backlayout = (LinearLayout) findViewById(R.id.edit_back_layout);
		backlayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		initImageOptions();
		initView();
		Config.isEditDrafts = true;
	}

	private void initImageOptions() {
		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new FadeInBitmapDisplayer(200))
				.bitmapConfig(Bitmap.Config.ALPHA_8).build();
	}

	public void initView() {
		// TODO Auto-generated method stub
		Intent intent=getIntent();
		id=intent.getStringExtra("id");
		DatebaseService service = new DatebaseService(context);
		News news=new News();
		news=service.queryDataById(Long.parseLong(id));
		picstr=news.getNewsPics();
		//分割字符串
		String[] splitPiclist = picstr.split(";");
		for (int i = 0; i < splitPiclist.length; i++) {
			if(FileUtil.fileExit(splitPiclist[i])){
				picList.add(splitPiclist[i]);
			}
		}
		picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
		title_et = (EditText) findViewById(R.id.title_hint_drafts);
		content_et = (EditText) findViewById(R.id.content_edt_drafts);
		title_et.setText(news.getTitle());
		content_et.setText(news.getContent());
		send_tv = (TextView) findViewById(R.id.submit_txt2_drafts);
		tv_save_drafts = (TextView) findViewById(R.id.tv_save_drafts_edite);
		send_tv.setOnClickListener(clickListener);
		tv_save_drafts.setOnClickListener(clickListener);
		gridview = (GridView) findViewById(R.id.gridview_drafts);
		picList.remove(0);
		gridview.setAdapter(new AddImageAdapter(picList, context, options));

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				if(Config.IS_SEND == true){
					return;
				}// 标记发布中)
				if (position == picList.size() - 1) {
					ActionSheetPic.showSheet(context, DraftsEditActivity.this);
				} else {

					Intent intent = new Intent(context, ImageViewActivity.class);
					intent.putExtra(ImageViewActivity.IMAGE_URL,
							picList.get(position));
					startActivityForResult(intent, Config.REQUEST_PREVIEW_PIC);
				}
			}

		});
	}

	OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.submit_txt2_drafts:
				pubNews();
				break;
			case R.id.tv_save_drafts_edite:

				saveDrafts();
				break;

			default:
				break;
			}
		}
	};
	BaseAdapter adapter = new BaseAdapter() {

		// 取得适配器中的视图
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// 将适配器中缓冲的视图控件返回
			View view = convertView;

			if (view == null) {
				// 将gallery_item.xml适配到View中
				LayoutInflater inflater = LayoutInflater.from(context);
				view = inflater.inflate(R.layout.grid_view_item, null);
			}

			// 查找gallery_item.xml中的ImageView控件
			ImageView imageView = (ImageView) view.findViewById(R.id.book_name);
			// imageView.setImageResource(picList.get(position));

			return view;
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public int getCount() {

			return picList.size();
		}
	};

	@Override
	public void onClick(int whichButton) {
		// TODO Auto-generated method stub
		switch (whichButton) {

		case R.id.local_pic:

			getLocalPohot();
			break;

		case R.id.take_photo:
			takePhoto();
			break;
		case R.id.cancel:
			break;

		default:
			break;
		}

	}

	private void takePhoto() {
		
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		cameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0); 
		String path = Config.TEMP_PATH;
		if (FileUtil.makeDir(path)) {

			String photoName = TimeUtil.dateToString(new Date(),
					TimeUtil.FORMAT_DATE_TIME_SECOND) + ".png";
			photPath = Config.TEMP_PATH + photoName;
			Uri imageUri = Uri.fromFile(new File(path, photoName));
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
			startActivityForResult(cameraIntent, 1);
		} else {

			ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.error_sdcard_null);
		}

	}

	private void getLocalPohot() {
		Intent intent = new Intent();
		intent.setClass(context, localImageFirstActivity.class);
		// List<String> tempList = picList;
		intent.putStringArrayListExtra("alredyChoose",
				(ArrayList<String>) picList);
		startActivityForResult(intent, Config.REQUEST_LOCAL_PIC);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// 相机返回
		if (resultCode == Activity.RESULT_OK) {
			picList.remove(picList.size() - 1);
			picList.add(photPath);
			picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
		// 预览activity 返回
		else if (resultCode == Config.RESULT_PREVIEW_PIC) {
			String path = data.getStringExtra(ImageViewActivity.IMAGE_URL);
			picList.remove(path);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
		// 本地照片 返回
		else if (resultCode == Config.RESULT_LOCAL_IMG) {

			picList = data.getStringArrayListExtra("alredyChoose");
			picList.add("drawable://" + R.drawable.qzone_photo_btn_add);
			AddImageAdapter adapter = new AddImageAdapter(picList, context,
					options);
			gridview.setAdapter(adapter);
		}
	}

	/**
	 * 存草稿
	 * 
	 * @param title
	 * @param content
	 */
	protected void saveDrafts() {
		
		
		if (TextUtils.isEmpty(title_et.getText())
				|| TextUtils.isEmpty(content_et.getText())) {

			ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.error_news_null);
			return;
		}
		if (title_et.getText().length() > 35) {
			ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.error_news_tolong);

			return;
		}
		if (picList.size()> 9) {
			
			ToastUtil.showErrorMsg((Activity)context, R.string.error_pic_tomuch);
			return;
		}
		String title = title_et.getText().toString();
		String content = content_et.getText().toString();
		//将List<String>转换为String[]
		StringBuffer sb = new StringBuffer();
		if(picList.size()>1){
			for(int i = 0; i < picList.size()-1; i++){
				
				if(i== picList.size()-2){
					sb. append(picList.get(i));
					
				}else{
					sb. append(picList.get(i)+";");
				}
				
			}
		}

		DatebaseService service = new DatebaseService(context);
		
		service.updateData(Long.parseLong(id), title, content, sb.toString());
		ToastUtil.showSuccessMsg((Activity)context, R.string.success_drafts);
		picList.clear();
		picList.add("drawable://"
				+ R.drawable.qzone_photo_btn_add);
		title_et.setText("");
		content_et.setText("");
		AddImageAdapter adapter = new AddImageAdapter(
				picList, context, options);
		gridview.setAdapter(adapter);
		
	}

	/**
	 * @Description 发布news 验证
	 */
	protected void pubNews() {
		// TODO Auto-generated method stub
		if (Config.IS_SEND) {
			ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.wait_send);
			return;
		}
		if (TextUtils.isEmpty(title_et.getText())
				|| TextUtils.isEmpty(content_et.getText())) {

			ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.error_news_null);
			return;
		}
		if (title_et.getText().length() > 35) {
			ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.error_news_tolong);

			return;
		}
		if (picList.size()> 9) {
			
			ToastUtil.showErrorMsg((Activity)context, R.string.error_pic_tomuch);
			return;
		}
		send_tv.setText(R.string.send_ing);
		
		Config.IS_SEND = true;// 标记发布中
		DatebaseService service = new DatebaseService(context);
		service.delData(Long.parseLong(id));
		final String title = title_et.getText().toString();
		final String content = content_et.getText().toString();
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (picList.size() > 1) {
					
					newsPicNum = picList.size()-1;
					for (int i =0;i<picList.size()-1 ;i++) {
						String picPath = picList.get(i);
						Bitmap camorabitmap = BitMapUtil
								.decodeBitmap(picPath, 600, 800);
						String filename = picPath
								.substring(picPath.lastIndexOf("/") + 1);
						File file = FileUtil.saveBitmap(Config.TEMP_PATH, filename,
								camorabitmap);// 压缩
						uploadPic(file,title, content);
					}

				}

				else {
					publishNews(title, content);
				}
			}
		},400);

	}

	/**
	 * @Description 上传图片
	 * @param file
	 */
	private void uploadPic(File file,final String title, final String content) {
		RequestParams params = new RequestParams();
		TwitterRestClient.client.addHeader("Content-Type",
				"multipart/form-data");
		try {
			params.put("file", file);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		TwitterRestClient.post(Config.AC_NEWS_PIC, params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1,
							byte[] response) {
						if (newPicPath != null) {
							newPicPath = newPicPath + new String(response)
									+ ";";
						} else {
							newPicPath = new String(response) + ";";
						}
						newsPicNum = newsPicNum - 1;
						if (newsPicNum == 0) {
							newPicPath = newPicPath.substring(0,
									newPicPath.length() - 1);
							publishNews(title, content);
						}
						
					}
				});
	}

	/**
	 * @Description 发布news
	 * @param title
	 * @param content
	 */
	private void publishNews(String title, String content) {
		RequestParams params = new RequestParams();
		params.put("news.title", title);
		params.put("news.content", content);
		if (newPicPath != null) {
			params.put("news.newsPics", newPicPath);
		}
		TwitterRestClient.post(Config.AC_NEWS_SEND, params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1,
							byte[] response, Throwable arg3) {
						// TODO Auto-generated method stub
						ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.fail_send);
						Config.IS_SEND = false;
						send_tv.setText(R.string.send);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] data) {
						// 发布完成
						String response = new String(data);
						if (response.indexOf(Config.SUCCESS) != -1) {
							picList.clear();
							picList.add("drawable://"
									+ R.drawable.qzone_photo_btn_add);
							title_et.setText("");
							content_et.setText("");
							AddImageAdapter adapter = new AddImageAdapter(
									picList, context, options);
							gridview.setAdapter(adapter);
							MyApplication.user.setNewsNum(MyApplication.user
									.getNewsNum() + 1);
							newPicPath=null;
							ToastUtil.showSuccessMsg(DraftsEditActivity.this, R.string.success_send);
							
						} else {
							ToastUtil.showErrorMsg(DraftsEditActivity.this, R.string.fail_send);

						}
						send_tv.setText(R.string.send);
						Config.IS_SEND = false;
					}
				});
	}

}
